package hy;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

public class Demo2 {
    static Jedis j=new Jedis("192.168.188.100",6379);
    @Test
    public void tranc1() throws InterruptedException {
        j.set("money","960");//可用额度
        j.set("debt","40");//欠债

        int consume=10;//本次信用卡消费额度
        j.watch("money");
        Thread.sleep(10000);
        int money= Integer.parseInt(j.get("money"));
        if(money<consume){
            j.unwatch();
            System.out.println("信用卡额度不够！");
            return;
        }
        System.out.println("**************事务开启***************");
        Transaction t=j.multi();
        t.incrBy("debt",consume);
        t.decrBy("money",consume);
        //集合中存放的是事务中变量的值
        List<Object> list= t.exec();
        if(list==null){
            System.out.println("事务失败，money被其他线程修改，请稍后再试");
        }
        j.unwatch();
        System.out.println("事务执行结束，当前余额："+j.get("money")+",欠帐："+j.get("debt"));
    }
}
